package com.ease.script.rhino;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

import javax.script.Bindings;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 
 * @author nathanleewei
 * 
 */
public class ApplicationContextBindings implements Bindings, ApplicationContextAware {

	private ApplicationContext applicationContext = null;

	protected void checkKey(Object key) {
		if (key == null) {
			throw new NullPointerException("key can not be null");
		}
		if (!(key instanceof String)) {
			throw new ClassCastException("key should be a String");
		}
		if (key.equals("")) {
			throw new IllegalArgumentException("key can not be empty");
		}
	}

	public Object get(Object key) {
		checkKey(key);
		Object object = null;
		if (null != applicationContext) {
			String beanName = String.valueOf(key);
			if (applicationContext.containsBean(beanName)) {
				object = applicationContext.getBean(String.valueOf(key));
			}
		}

		return object;
	}

	public Object put(String name, Object value) {
		return null;
	}

	public void putAll(Map<? extends String, ? extends Object> toMerge) {
	}

	public Object remove(Object key) {
		return null;
	}

	public void clear() {
	}

	public boolean containsKey(Object key) {
		boolean b = false;
		if (null != applicationContext) {
			b = applicationContext.containsBean(String.valueOf(key));
		}
		return b;
	}

	public boolean containsValue(Object value) {
		return false;
	}

	public Set<java.util.Map.Entry<String, Object>> entrySet() {
		return null;
	}

	public boolean isEmpty() {
		return true;
	}

	public Set<String> keySet() {
		return null;
	}

	public int size() {
		return applicationContext.getBeanDefinitionCount();
	}

	public Collection<Object> values() {
		return null;
	}

	/**
	 * @return the applicationContext
	 */
	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * @param applicationContext
	 *            the applicationContext to set
	 */
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

}
